<template>
  <n-card
    title="Boolean Wing"
    style="height: 100vh; display: flex; flex-direction: column; padding: 0"
  >
    <template #header-extra>
      <n-button quaternary type="error" size="small" @click="handleClean"> 清理 </n-button>
      <n-popover trigger="click">
        <template #trigger>
          <n-button quaternary size="small" @click="handleClean"> ？ </n-button>
        </template>
        <div>
          <p>Shift+单击：将点击的文本快速添加到记事本</p>
          <p>Alt+单击：将点击的文本快速填充至AI提问框</p>
          <p>Shift+Alt+W：将选中的文本快速添加到记事本</p>
        </div>
      </n-popover>
    </template>

    <template v-if="authorization !== 'fail'">
      <!-- 聊天区域 -->
      <div
        ref="chatArea"
        style="
          flex: 1;
          overflow-y: auto;
          max-height: 55vh;
          padding: 16px;
          background-color: #f5f7fa;
        "
      >
        <div style="margin-bottom: 12px">
          <div :style="botStyle">
            <p style="white-space: pre-line">
              {{ aiResponeData || '答案仅供参考，请务必调整...' }}
            </p>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div style="padding: 12px">
        <n-space>
          <n-radio-group
            v-model:value="aiModel"
            name="aiModel"
            size="small"
            @update:value="changeAiModelHandle"
          >
            <n-radio v-for="item in aiModelList" :key="item.value" :value="item.value">
              {{ item.alias }}
            </n-radio>
          </n-radio-group>
        </n-space>
        <div style="padding-top: 12px; display: flex; gap: 8px">
          <n-input
            v-model:value="innerHTML"
            placeholder="输入消息..."
            type="textarea"
            style="flex: 1"
            :autosize="{ minRows: 3, maxRows: 6 }"
          />

          <div
            class="btn-area"
            style="display: flex; flex-direction: column; justify-content: space-around"
          >
            <!-- 发送按钮 -->
            <n-button type="primary" @click="handleSend" :loading="loading">AI</n-button>
            <n-button type="default" :loading="loading" @click="handleAddNote">记</n-button>
            <!-- <div style="display: flex; justify-content: space-around">
              <n-button size="small" type="default" :loading="loading" @click="handleAddNote"
                >记</n-button
              >
              <n-button size="small" type="default" :loading="loading" @click="handleOcr"
                >截</n-button
              >
            </div> -->
          </div>
        </div>
      </div>
    </template>
    <template v-else>
      <span style="color: red">未授权，找二毛</span>
    </template>

    <div class="note" style="padding: 12px">
      <h4 style="margin-top: 0; margin-bottom: 0">记事本</h4>
      <n-input
        v-model:value="kkNote"
        placeholder="记事本..."
        type="textarea"
        style="flex: 1"
        @input="handleNote"
        :autosize="{ minRows: 3, maxRows: 6 }"
      />
    </div>
    <div class="extra" style="padding: 12px">
      <h4 style="margin-top: 0; margin-bottom: 8px; display: flex; justify-content: space-between">
        <div>扩展信息</div>
        <div style="cursor: pointer; text-align: right" @click="getInnDetail">|</div>
      </h4>
      <n-collapse @item-header-click="handleExtraClick">
        <n-collapse-item title="数据一" name="1">
          <div>{{ extraData1 }}</div>
          <div>{{ extraData2 }}</div>
        </n-collapse-item>
        <!-- <n-collapse-item title="数据二" name="2">
          <div>{{ extraData2 }}</div>
        </n-collapse-item> -->
      </n-collapse>
    </div>
  </n-card>
</template>

<script setup lang="ts">
import { ref, shallowRef, toRaw, onMounted, nextTick } from 'vue'
import {
  useMessage,
  NCard,
  NInput,
  NButton,
  NRadioGroup,
  NPopover,
  NSpace,
  NRadio,
  NCollapse,
  NCollapseItem,
} from 'naive-ui'
import { aiModels, aiModelsForJGB, teamType } from '../config/index'
import {
  getItem,
  setItem,
  generateUUID,
  removeItem,
  isOnlineImageUrl,
  innReqParams,
} from '../utils'

const innerHTML = ref('')
const chatArea = ref(null)

const botStyle = {
  backgroundColor: '#d0ebff',
  padding: '10px 14px',
  borderRadius: '8px',
  maxWidth: '100%',
  marginRight: 'auto',
}

const editorKey = shallowRef(0)
const loading = shallowRef(false)

let aiRespone = shallowRef({})
const aiResponeData = ref(``)

let extraData1: any = ref('')
let extraData2: any = ref('')
const handleExtraClick = async (a: any) => {
  if (a.name === '1') {
    let innGpid = await getItem('innGpid')
    console.log('innGpid: ', innGpid);
    extraData1 = innGpid
  }
  if (a.name === '2') {
    let innovatemrRepDetail = await getItem('innovatemrDetail')
    extraData2 = innovatemrRepDetail
    // extraData2 = JSON.stringify(innovatemrRepDetail, null, 2);
  }
}

const getInnDetail = async () => {
  let url: any = await getItem('innovatemrDetail')
  if (!url) return

  chrome.tabs.query({ active: true, currentWindow: true }, (tabs: any) => {
    chrome.tabs.sendMessage(tabs[0].id, {
      action: 'inn_check_detail',
    })
    setTimeout(async () => {
      let data: any = await getItem('inn_detail')
      extraData2 = JSON.stringify(data, null, 2)
    }, 5000)
  })
}

const sendMessageHandle = async (content?: string) => {
  aiResponeData.value = ''
  let innerHTMLs = content || innerHTML.value
  if (!innerHTMLs) return ''
  loading.value = true

  // 如果是图片链接则不发送
  if (isOnlineImageUrl(innerHTMLs)) {
    chrome.runtime.sendMessage(
      { action: 'CREATE_MESSAGE_FLOAT_IMAGE', data: innerHTMLs },
      function (response) {
        editorKey.value += 1
        if (response.status && response.msg.code === 0) {
          aiRespone.value = response.msg
          aiResponeData.value = response.msg.data
        } else {
          aiResponeData.value = `ERROR ${response.msg?.msg || response.msg}`
        }
        loading.value = false
      },
    )
    return
  }

  chrome.runtime.sendMessage(
    { action: 'CREATE_MESSAGE_FLOAT', data: innerHTMLs },
    function (response) {
      editorKey.value += 1
      if (response.status && response.msg.code === 0) {
        aiRespone.value = response.msg
        aiResponeData.value = response.msg.data
        setItem('aiResponeData', response.msg.data)
      } else {
        aiResponeData.value = `ERROR ${response.msg?.msg || response.msg}`
      }
      loading.value = false
    },
  )
}

const handleSend = async () => {
  if (!innerHTML.value.trim()) return
  if (!aiModel.value) {
    aiResponeData.value = `请先选个模型吧`
    return
  }
  sendMessageHandle()
}

const handleClean = async () => {
  aiResponeData.value = ''
  innerHTML.value = ''
  removeItem('selectedText')
  removeItem('aiResponeData')
}

let isStream: any = ref(true)
const streamChange = async () => {
  setItem('isStream', isStream.value)
}

let authorization: any = ref('fail')
const aiModel: any = ref('doubao')
const aiModelList: any = ref([])

const handleNote = async (value: any) => {
  if (!value) return ''
  setItem('kkNote', value)
}

const handleAddNote = async () => {
  if (!innerHTML.value) return ''
  loading.value = true
  let value = kkNote.value + '\n' + innerHTML.value
  kkNote.value = value
  setItem('kkNote', value)
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const handleOcr = async () => {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
  if (tab.id !== undefined) {
    chrome.tabs.sendMessage(tab.id, { action: 'START_SELECT' })
  } else {
    console.error('Tab ID is undefined')
  }
}

const changeAiModelHandle = async (value: any) => {
  let _target = aiModelList.value.find((item: any) => {
    return item.value === value
  })
  let target = toRaw(_target)
  aiModel.value = target.value
  if (aiModel.value) {
    setItem('aiModel', aiModel.value)
    setItem('AIMODEL', target)
  }
}
const chooseAiModel = async () => {
  getItem('authorization').then((result) => {
    authorization.value = result || 'fail'
    // if (result === 'pass') {
    //   aiModelList.value = aiModels;
    // } else {
    //   aiModelList.value = aiModels.filter((item) => !item.premium);
    // }
    aiModelList.value = aiModels
    if (teamType === 'buer') {
      aiModelList.value = aiModels
    } else {
      aiModelList.value = aiModelsForJGB
    }
    getItem('aiModel').then((result) => {
      aiModel.value = result || 'c1'
      if (!result) {
        let allowModes = aiModelList.value.filter((item: any) => {
          return !item.label.includes('全能')
        })
        let target = allowModes[Math.floor(Math.random() * allowModes.length)]
        if (target) {
          aiModel.value = target.value
          setItem('aiModel', aiModel.value)
          setItem('AIMODEL', target)
        }
      }
    })
  })
}

let kkNote: any = ref('')
let zipcode = ref('')
let city = ref('')
const booleanUid = ref('')
onMounted(async () => {
  chrome.runtime.onMessage.addListener(function (request) {
    if (request.action === 'STREAMANSWER') {
      aiResponeData.value += request.data
      loading.value = false
    }
    if (request.action === 'selectedText') {
      if (request.data && request.data.length >= 15) {
        setItem('selectedText', request.data)
        innerHTML.value = request.data
      }
    }

    if (request.action === 'selectedTextAll') {
      if (request.data && request.data.length >= 0) {
        setItem('selectedText', request.data)
        innerHTML.value = request.data
      }
    }

    if (request.action === 'setInnGpid') {
      if (request.data) {
        extraData1.value = request.data
      }
    }

    if (request.action === 'selectedTextAddNote') {
      if (request.data) {
        getItem('kkNote').then((result: any) => {
          if (result) {
            kkNote.value = `${result}`
          }
        })
      }
    }
  })

  // 检查是否已经生成过唯一ID
  try {
    let sc: any = await getItem('booleanUid')
    // booleanUid.value = sc
    if (!sc) {
      booleanUid.value = generateUUID()
      setItem('booleanUid', booleanUid.value)
    }
  } catch (error) {
    console.log('error: ', error)
    const booleanUid = generateUUID()
    setItem('booleanUid', booleanUid)
  }
  getItem('isStream').then((result) => {
    isStream.value = result
  })

  getItem('aiResponeData').then((result: any) => {
    if (result) {
      aiResponeData.value = result
    }
  })

  getItem('selectedText').then((result: any) => {
    if (result) {
      innerHTML.value = result
    }
  })

  getItem('innGpid').then((result: any) => {
    if (result) {
      extraData1.value = result
    }
  })

  getItem('kkNote').then((result: any) => {
    if (result) {
      kkNote.value = `${result}`
    }
  })

  // 获取本地信息
  getItem('ipinfo').then((value: any) => {
    if (value) {
      // ipinfo.value = value
      if (value.ip_data) {
        zipcode.value = value.ip_data.zipcode
        city.value = value.ip_data.region
      }
    }
  })

  chooseAiModel()
})
</script>
